package com.weimob.mcloud.wechatwork.customer.job;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.weimob.elasticjob.annotation.ElasticJob;
import com.weimob.elasticjob.executor.context.ExecutorContext;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.WechatWorkEmployeeExport;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.data.OrgUserSimpleBO;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.req.EmployeeDTO;
import com.weimob.marketing.syswechatworkusermanagement.wechatworkusermanagement.service.user.dto.req.base.IterativePage;
import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.employee.EmployeeActiveStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.employee.EmployeeStatusEnum;
import com.weimob.mcloud.wechatwork.core.service.privatesphere.PrivateSphereService;
import com.weimob.mcloud.wechatwork.customer.mq.handler.employee.EmployeeAuthorizeChangeHandler;
import com.weimob.soa.common.response.SoaResponse;
import com.weimob.soa.common.utils.SoaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 客户全量更新授权状态job
 *
 * @author yuanhao
 * @date 2023/4/19 19:28
 */
@Slf4j
@Component
public class CustomerAuthorizeJob {
    @Reference
    WechatWorkEmployeeExport wechatWorkEmployeeExport;

    @Autowired
    private EmployeeAuthorizeChangeHandler employeeAuthorizeChangeHandler;

    @Reference
    private PrivateSphereService privateSphereService;


    @ElasticJob(name = "flushCustomerAuthorizedStatusByEmployee")
    public void flushCustomerStatus(ExecutorContext executorContext) {
        Map<String, String> map = executorContext.getTriggerCustomParameter();
        log.info("flushCustomerStatus start,param:{}", JSON.toJSONString(map));
        String corpId = map.get("corpId");
        if (StringUtils.isBlank(corpId)) {
            log.error("flushCustomerStatus corpId is null ,{}", JSON.toJSONString(map));
            return;
        }
        String bosId = map.get("bosId");
        if (StringUtils.isBlank(bosId)) {
            log.error("flushCustomerStatus bosId  is null ,{}", JSON.toJSONString(map));
            return;
        }
        PrivateSphere privateSphere = new PrivateSphere();
        privateSphere.setCorpId(corpId);
        privateSphere.setBosId(Long.valueOf(bosId));
        SoaResponse<PrivateSphere, Void> fetchPrivateSphere = privateSphereService.simpleFetch(privateSphere);
        if (!SoaUtil.isSucc(fetchPrivateSphere) || Objects.isNull(fetchPrivateSphere.getResponseVo())) {
            log.info("处理员工授权范围变更/坐席变更，查询私域信息失败,corpId:{}", corpId);
            return;
        }
        privateSphere = fetchPrivateSphere.getResponseVo();

        String employeeId = map.get("employeeId");
        IterativePage<EmployeeDTO, String> iterativePage = new IterativePage<>();
        EmployeeDTO employeeDTO = new EmployeeDTO();
        employeeDTO.setCorpId(corpId);
        employeeDTO.setBosId(privateSphere.getBosId());
        if (StringUtils.isNotBlank(employeeId)) {
            employeeDTO.setEmployeeId(employeeId);
        }
        employeeDTO.setExceptDeleted(true);
        employeeDTO.setDeleted(false);
        iterativePage.setData(employeeDTO);
        iterativePage.setPageOrderByParam("employee_id");

        SoaResponse<List<OrgUserSimpleBO>, ?> employeePagination;
        int maxLoopSize = 1000;
        int loopSize = 0;
        String lastEmployeeId = null;
        while (loopSize < maxLoopSize) {
            loopSize++;
            //设置游标
            iterativePage.setLastOrderByFieldValue(lastEmployeeId);
            //滚动查询
            employeePagination = wechatWorkEmployeeExport.getEmployeePagination(iterativePage);
            if (!SoaUtil.isSucc(employeePagination) || CollectionUtils.isEmpty(employeePagination.getResponseVo())) {
                break;
            }
            List<OrgUserSimpleBO> responseVo = employeePagination.getResponseVo();
            //游标赋值
            lastEmployeeId = responseVo.get(responseVo.size() - 1).getOrgUserId();
            //业务处理
            bizHandler(responseVo, privateSphere);
        }
        log.info("flushCustomerAuthorizedStatusByEmployee is complete,corpId:{}", corpId);
    }



    private void bizHandler(List<OrgUserSimpleBO> responseVo, PrivateSphere privateSphere) {
        //拿到员工ids，根据状态合并后做分类
        List<String> unAuthEmpIds = new ArrayList<>();
        List<String> authEmpIds = new ArrayList<>();
        for (OrgUserSimpleBO orgUserSimpleBO : responseVo) {
            if (Objects.isNull(orgUserSimpleBO)) {
                continue;
            }
            //获取员工的状态->合并出客户状态
            Integer status = orgUserSimpleBO.getStatus();
            Integer activeStatus = orgUserSimpleBO.getActiveStatus();
            String id = orgUserSimpleBO.getOrgUserId();
            if (EmployeeStatusEnum.USER_UN_AUTHORIZATION.getCode() == status
                    || EmployeeActiveStatusEnum.INACTIVE.getCode() == activeStatus) {
                unAuthEmpIds.add(id);
            } else {
                authEmpIds.add(id);
            }
        }

        //根据员工终态状态分类处理
        if (CollectionUtils.isNotEmpty(authEmpIds)) {
            //授权-则需要查询未授权的客户再去修改
            employeeAuthorizeChangeHandler.handleAuthorizeByCustomerStatus(authEmpIds, privateSphere, CustomerStatusEnum.UNAUTHORIZED);
        }

        if (CollectionUtils.isNotEmpty(unAuthEmpIds)) {
            //未授权-则需要查询已授权的客户再去修改
            employeeAuthorizeChangeHandler.handleAuthorizeByCustomerStatus(unAuthEmpIds, privateSphere, CustomerStatusEnum.DEFAULT);
        }
    }
}
